import axios, { AxiosInstance } from "axios";
import { getToken } from "../store";
import router from "../router";

declare global {
	interface Window {
		$http: AxiosInstance;
	}
}

const http = axios.create({
	baseURL: import.meta.env.VITE_API_URL,
	timeout: 1000 * 60 * 10,
});

http.interceptors.request.use(
	(config) => {
		const token = getToken();
		if (token) {
			config.headers["Authorization"] = `Bearer ${token}`;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

http.interceptors.response.use(
	(response) => {
		return response;
	},
	async (error) => {
		if (error.response?.status === 401) {
			router.push("/login");
		}

		return Promise.reject(error);
	}
);

export default http;
